import React, { useState, useEffect } from 'react';
import { 
  Card, 
  Table, 
  Button, 
  Space, 
  Tag, 
  Modal, 
  Form, 
  Input, 
  Select, 
  DatePicker, 
  Statistic,
  Row,
  Col,
  Divider,
  message,
  Popconfirm
} from 'antd';
import { 
  PlusOutlined, 
  SearchOutlined, 
  ReloadOutlined,
  ExportOutlined,
  DollarOutlined,
  ShoppingCartOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import { paymentApi } from '@/services/api';
import type { PaymentOrder, PaymentStatus } from '@/types';
import dayjs from 'dayjs';

const { RangePicker } = DatePicker;
const { Option } = Select;

const PaymentManagement: React.FC = () => {
  const [form] = Form.useForm();
  const [createForm] = Form.useForm();
  const [searchParams, setSearchParams] = useState({
    page: 1,
    pageSize: 10,
  });
  const [createModalVisible, setCreateModalVisible] = useState(false);
  const [ordersData, setOrdersData] = useState<any>(null);
  const [statsData, setStatsData] = useState<any>(null);
  const [loading, setLoading] = useState(false);
  const [createLoading, setCreateLoading] = useState(false);

  // 获取订单列表
  const fetchOrders = async () => {
    setLoading(true);
    try {
      const response = await paymentApi.getOrders(searchParams);
      setOrdersData(response);
    } catch (error) {
      message.error('获取订单列表失败');
    } finally {
      setLoading(false);
    }
  };

  // 获取统计数据
  const fetchStats = async () => {
    try {
      const response = await paymentApi.getPaymentStats([
        dayjs().subtract(30, 'day').format('YYYY-MM-DD'),
        dayjs().format('YYYY-MM-DD')
      ]);
      setStatsData(response);
    } catch (error) {
      message.error('获取统计数据失败');
    }
  };

  // 创建订单
  const createOrder = async (values: any) => {
    setCreateLoading(true);
    try {
      await paymentApi.createOrder(values);
      message.success('订单创建成功');
      setCreateModalVisible(false);
      createForm.resetFields();
      fetchOrders();
    } catch (error: any) {
      message.error(error.message || '创建订单失败');
    } finally {
      setCreateLoading(false);
    }
  };

  // 取消订单
  const cancelOrder = async (id: number) => {
    try {
      await paymentApi.cancelOrder(id);
      message.success('订单取消成功');
      fetchOrders();
    } catch (error: any) {
      message.error(error.message || '取消订单失败');
    }
  };

  // 退款
  const refundOrder = async (id: number, reason?: string) => {
    try {
      await paymentApi.refundOrder(id, reason);
      message.success('退款申请已提交');
      fetchOrders();
    } catch (error: any) {
      message.error(error.message || '退款申请失败');
    }
  };

  useEffect(() => {
    fetchOrders();
  }, [searchParams]);

  useEffect(() => {
    fetchStats();
  }, []);

  const getStatusTag = (status: PaymentStatus) => {
    const statusMap = {
      pending: { color: 'orange', text: '待支付' },
      success: { color: 'green', text: '支付成功' },
      failed: { color: 'red', text: '支付失败' },
      cancelled: { color: 'gray', text: '已取消' },
    };
    const config = statusMap[status] || { color: 'default', text: status };
    return <Tag color={config.color}>{config.text}</Tag>;
  };

  const getPaymentMethodTag = (method: string) => {
    const methodMap = {
      alipay: { color: 'blue', text: '支付宝' },
      wechat: { color: 'green', text: '微信支付' },
      bank: { color: 'purple', text: '银行卡' },
    };
    const config = methodMap[method] || { color: 'default', text: method };
    return <Tag color={config.color}>{config.text}</Tag>;
  };

  const columns: ColumnsType<PaymentOrder> = [
    {
      title: '订单号',
      dataIndex: 'orderNo',
      key: 'orderNo',
      width: 180,
      render: (text) => <code>{text}</code>,
    },
    {
      title: '金额',
      dataIndex: 'amount',
      key: 'amount',
      width: 120,
      render: (amount) => <span style={{ color: '#f50' }}>¥{amount}</span>,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: getStatusTag,
    },
    {
      title: '支付方式',
      dataIndex: 'paymentMethod',
      key: 'paymentMethod',
      width: 120,
      render: getPaymentMethodTag,
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
      ellipsis: true,
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      width: 180,
      render: (time) => dayjs(time).format('YYYY-MM-DD HH:mm:ss'),
    },
    {
      title: '完成时间',
      dataIndex: 'completeTime',
      key: 'completeTime',
      width: 180,
      render: (time) => time ? dayjs(time).format('YYYY-MM-DD HH:mm:ss') : '-',
    },
    {
      title: '操作',
      key: 'action',
      width: 200,
      render: (_, record) => (
        <Space size="small">
          {record.status === 'pending' && (
            <Popconfirm
              title="确定要取消这个订单吗？"
              onConfirm={() => cancelOrder(record.id)}
              okText="确定"
              cancelText="取消"
            >
              <Button size="small" danger>
                取消
              </Button>
            </Popconfirm>
          )}
          {record.status === 'success' && (
            <Popconfirm
              title="确定要申请退款吗？"
              onConfirm={() => refundOrder(record.id, '用户申请退款')}
              okText="确定"
              cancelText="取消"
            >
              <Button size="small" type="primary" ghost>
                退款
              </Button>
            </Popconfirm>
          )}
          <Button size="small" type="link">
            详情
          </Button>
        </Space>
      ),
    },
  ];

  const handleSearch = (values: any) => {
    const params = {
      ...searchParams,
      page: 1,
      ...values,
    };
    
    if (values.dateRange) {
      params.startDate = values.dateRange[0].format('YYYY-MM-DD');
      params.endDate = values.dateRange[1].format('YYYY-MM-DD');
      delete params.dateRange;
    }
    
    setSearchParams(params);
  };

  const handleCreateOrder = (values: any) => {
    createOrder(values);
  };

  const refresh = fetchOrders;

  const handleTableChange = (pagination: any) => {
    setSearchParams({
      ...searchParams,
      page: pagination.current,
      pageSize: pagination.pageSize,
    });
  };

  return (
    <div style={{ padding: '24px' }}>
      {/* 统计卡片 */}
      <Row gutter={16} style={{ marginBottom: '24px' }}>
        <Col xs={24} sm={12} md={6}>
          <Card>
            <Statistic
              title="总订单数"
              value={statsData?.data?.totalOrders || 0}
              prefix={<ShoppingCartOutlined />}
              valueStyle={{ color: '#1890ff' }}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} md={6}>
          <Card>
            <Statistic
              title="成功订单"
              value={statsData?.data?.successOrders || 0}
              prefix={<CheckCircleOutlined />}
              valueStyle={{ color: '#52c41a' }}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} md={6}>
          <Card>
            <Statistic
              title="总收入"
              value={statsData?.data?.totalRevenue || 0}
              precision={2}
              prefix={<DollarOutlined />}
              suffix="¥"
              valueStyle={{ color: '#f5222d' }}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} md={6}>
          <Card>
            <Statistic
              title="成功率"
              value={statsData?.data?.successRate || 0}
              precision={2}
              suffix="%"
              valueStyle={{ color: '#722ed1' }}
            />
          </Card>
        </Col>
      </Row>

      <Card>
        {/* 搜索表单 */}
        <Form
          form={form}
          layout="inline"
          onFinish={handleSearch}
          style={{ marginBottom: '16px' }}
        >
          <Form.Item name="keyword">
            <Input placeholder="订单号/描述" style={{ width: 200 }} />
          </Form.Item>
          <Form.Item name="status">
            <Select placeholder="订单状态" style={{ width: 120 }} allowClear>
              <Option value="pending">待支付</Option>
              <Option value="success">支付成功</Option>
              <Option value="failed">支付失败</Option>
              <Option value="cancelled">已取消</Option>
            </Select>
          </Form.Item>
          <Form.Item name="paymentMethod">
            <Select placeholder="支付方式" style={{ width: 120 }} allowClear>
              <Option value="alipay">支付宝</Option>
              <Option value="wechat">微信支付</Option>
              <Option value="bank">银行卡</Option>
            </Select>
          </Form.Item>
          <Form.Item name="dateRange">
            <RangePicker />
          </Form.Item>
          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
                搜索
              </Button>
              <Button 
                onClick={() => {
                  form.resetFields();
                  setSearchParams({ page: 1, pageSize: 10 });
                }}
              >
                重置
              </Button>
            </Space>
          </Form.Item>
        </Form>

        <Divider />

        {/* 操作按钮 */}
        <div style={{ marginBottom: '16px' }}>
          <Space>
            <Button
              type="primary"
              icon={<PlusOutlined />}
              onClick={() => setCreateModalVisible(true)}
            >
              创建订单
            </Button>
            <Button icon={<ReloadOutlined />} onClick={fetchOrders}>
              刷新
            </Button>
            <Button icon={<ExportOutlined />}>
              导出
            </Button>
          </Space>
        </div>

        {/* 订单表格 */}
        <Table
          columns={columns}
          dataSource={ordersData?.data?.list || []}
          loading={loading}
          rowKey="id"
          pagination={{
            current: ordersData?.data?.page || 1,
            pageSize: ordersData?.data?.pageSize || 10,
            total: ordersData?.data?.total || 0,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条记录`,
          }}
          onChange={handleTableChange}
          scroll={{ x: 1200 }}
        />
      </Card>

      {/* 创建订单弹窗 */}
      <Modal
        title="创建支付订单"
        open={createModalVisible}
        onOk={() => createForm.submit()}
        onCancel={() => setCreateModalVisible(false)}
        confirmLoading={createLoading}
        width={600}
      >
        <Form
          form={createForm}
          layout="vertical"
          onFinish={handleCreateOrder}
        >
          <Form.Item
            name="amount"
            label="订单金额"
            rules={[
              { required: true, message: '请输入订单金额' },
              { type: 'number', min: 0.01, max: 999999.99, message: '金额范围：0.01-999999.99' },
            ]}
          >
            <Input
              type="number"
              step="0.01"
              placeholder="请输入订单金额"
              addonBefore="¥"
            />
          </Form.Item>
          
          <Form.Item
            name="paymentMethod"
            label="支付方式"
            rules={[{ required: true, message: '请选择支付方式' }]}
          >
            <Select placeholder="请选择支付方式">
              <Option value="alipay">支付宝</Option>
              <Option value="wechat">微信支付</Option>
              <Option value="bank">银行卡</Option>
            </Select>
          </Form.Item>
          
          <Form.Item
            name="description"
            label="订单描述"
          >
            <Input.TextArea
              rows={3}
              placeholder="请输入订单描述"
              maxLength={255}
            />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default PaymentManagement;